package com.strp.mptcp.ACK;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;

import java.util.Set;

/**
 * 选择性 ACK 头，包类型 = 2，跟随一个 int 类型的缺失序号个数，以及若干 long 类型的序列号。
 */
public class SelectiveAckHeader {
    public static final byte TYPE = 2;
    private final long largestContiguousSeq;
    private final Set<Long> receivedSeqs;

    /**
     * @param largestContiguousSeq 最大连续 seq
     * @param receivedSeqs 已接收的乱序 seq 集合
     */
    public SelectiveAckHeader(long largestContiguousSeq, Set<Long> receivedSeqs) {
        this.largestContiguousSeq = largestContiguousSeq;
        this.receivedSeqs = receivedSeqs;
    }

    public ByteBuf toByteBuf() {
        int count = receivedSeqs.size();
        ByteBuf buf = ByteBufAllocator.DEFAULT.buffer(1 + 8 + 4 + count * 8);
        buf.writeByte(TYPE);
        buf.writeLong(largestContiguousSeq);
        buf.writeInt(count);
        for (Long seq : receivedSeqs) {
            buf.writeLong(seq);
        }
        return buf;
    }
}
